<template>
  <div class="aewave-container">
    <div ref="chartContainer" class="waveform-container"></div>
    <!-- 参数区域 -->
    <div v-if="showParams && params.length > 0" class="params-container">
      <div class="params-scroll">
        <div v-for="(param, index) in params" :key="index" class="param-item">
          <span class="param-name">{{ param.label}}:</span>
          <span class="param-value">{{ param.value +" "+param.unit }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, toRaw } from "vue";
import * as Plotly from 'plotly.js-dist-min';
import type { PlotData, Layout, Config } from 'plotly.js';

// 定义组件 props
const props = defineProps({
  title: {
    type: String,
    default: 'Waveform'
  },
  xAxisUnit: {
    type: String,
    default: ''
  },
  xAxisData: {
    type: Array<number | string>,
    required: false,
    default: [],
  },
  yAxisUnit: {
    type: String,
    default: ''
  },
  yAxisData: {
    type: Array<number>,
    required: false,
    default: [],
  },
  showParams: {
    type: Boolean,
    default: false
  },
  params: {
    type: Array<{
      val: string;
      label: string;
      unit: string;
      value: string;
    }>,
    default: () => []
  },
  renderFlag:{
    type: Number,
    required: false,
    default: 0,
  }
});

watch(
  () => props,
  (newParams) => {

  },
  {deep: true, immediate: true}
)

// 图表容器引用
const chartContainer = ref<HTMLDivElement | null>(null);
// 图表实例引用
let chartInstance: Plotly.PlotlyHTMLElement | null = null;

// 窗口大小变化处理函数
const handleResize = () => {
  if (chartInstance) {
    Plotly.relayout(chartInstance, {
      width: chartContainer.value?.offsetWidth || undefined,
      height: chartContainer.value?.offsetHeight || undefined
    });
  }
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value || !props.xAxisData.length || !props.yAxisData.length) {
    return;
  }

  // 准备图表数据
  const trace: PlotData = {
    x: props.xAxisData,
    y: props.yAxisData,
    type: 'scatter',
    mode: 'lines',
    line: {
      color: '#1890ff',
      width: 2
    }
  };

  // 图表布局
  const layout: Layout = {
    title: {
      text: props.title,
      font: {
        size: 12
      }
    },
    xaxis: {
      title: {
        text: `X轴${props.xAxisUnit ? ` (${props.xAxisUnit})` : ''}`
      },
      showgrid: true,
      gridcolor: '#eee'
    },
    yaxis: {
      title: {
        text: `Y轴${props.yAxisUnit ? ` (${props.yAxisUnit})` : ''}`
      },
      showgrid: true,
      gridcolor: '#eee'
    },
    margin: {
      l: 50,
      r: 50,
      t: 25,
      b: 15
    },
    responsive: true,
    width: chartContainer.value.offsetWidth,
    height: chartContainer.value.offsetHeight
  };

  // 图表配置
  const config: Config = {
    displayModeBar: true,
    responsive: true,
    scrollZoom: true,
    toImageButtonOptions: {
      format: 'png',
      filename: props.title || 'waveform',
      height: chartContainer.value.offsetHeight,
      width: chartContainer.value.offsetWidth,
      scale: 2
    }
  };

  // 渲染图表
  Plotly.newPlot(
    chartContainer.value,
    [trace],
    layout,
    config
  ).then(plot => {
    chartInstance = plot;
  });
};

// 监听 props 变化，更新图表
watch(() => props.renderFlag, (newVal, oldVal) => {
  if (newVal > 0) {
    if(!chartInstance) {
      nextTick(() => {
        initChart();
        window.addEventListener('resize', handleResize);
      });
    }
    if (chartInstance) {
      // 更新数据
      Plotly.update(chartInstance, {
        x: [props.xAxisData],
        y: [props.yAxisData]
      }, {
        title: {
          text: props.title
        },
        xaxis: {
          title: {
            text: `X轴${props.xAxisUnit ? ` (${props.xAxisUnit})` : ''}`
          }
        },
        yaxis: {
          title: {
            text: `Y轴${props.yAxisUnit ? ` (${props.yAxisUnit})` : ''}`
          }
        }
      });
    }
  }
});

// 组件挂载时初始化图表和事件监听
onMounted(() => {
  nextTick(() => {
    initChart();
    window.addEventListener('resize', handleResize);
  });
});

// 组件卸载时清理图表和事件监听
onUnmounted(() => {
  if (chartInstance) {
    Plotly.purge(chartInstance);
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="scss">
.aewave-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.waveform-container {
  width: 100%;
  height: 100%;
  min-height: 150px;
}

.params-container {
  margin-top: 3px;
  padding: 3px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.params-scroll {
  max-height: 100px; /* 大约3行的高度 */
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.param-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  padding: 1px 1px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  white-space: nowrap;
  font-size: 11px;
  font-weight: bold;
}

.param-name {
  margin-right: 3px;
}

.param-value {
  color: #666;
}
</style>
